//
//  InvitationManager.m
//  CandyCrushClone
//
//  Created by Petar on 2/10/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "InvitationManager.h"
#import "Globals.h"
#import <SFS2XAPIIOS/SmartFox2XClient.h>


@interface InvitationManager () <UIAlertViewDelegate>


@end


@implementation InvitationManager
{
    CommunicationManager *_communicationManager;
    __weak SmartFox2XClient *_smartFoxClient;
    SFSInvitation *_invitation;
    SFSUser *_inviter;
}


- (instancetype)initWithCommunicationManager:(CommunicationManager *)communicationManager andSFSClient:(SmartFox2XClient *)sfsClient
{
    self = [super init];
    if (self) {
        
        _smartFoxClient = sfsClient;
        _communicationManager = communicationManager;
        
    }
    return self;
}


-(void)inviteUserToBuddyList:(NSString *)username
{

    // set Invitee name as parameter
    SFSObject *sfsInvitee = [SFSObject new];
    [sfsInvitee putUtfString:INVITEE_NAME value:username];
    
    // Do NOT send Invitation if you have already Added this User in your BuddyList
    NSArray *buddies = [_communicationManager getBuddyList];
    for (SFSBuddy *buddy in buddies) {
        if ( [buddy.name isEqualToString:username] ) {
            
            NSString *message = [NSString stringWithFormat:@"%@ is already your buddy.", username];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Buddy Invitation" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alertView show];
            return;
        }
    }
    
    // Send ExtensionRequest with InviteeName as params
    [_smartFoxClient send:[ExtensionRequest requestWithExtCmd:CMD_INVITE_USER_TO_BUDDYLIST params:sfsInvitee]];
    
}


// Invite buddy to play game together
-(void)inviteBuddyToPlayGame:(NSString *)buddyname
{

    // set Invitee name as parameter
    SFSObject *sfsInvitee = [SFSObject new];
    [sfsInvitee putUtfString:INVITEE_NAME value:buddyname];
    
    // Send ExtensionRequest with InviteeName as params
    [_smartFoxClient send:[ExtensionRequest requestWithExtCmd:CMD_INVITE_BUDDY_TO_PLAY_GAME params:sfsInvitee]];
    
}


// Called when someone sent you SFSInvitation
-(void)onInvitation:(SFSEvent *)evt
{
    
    // Can NOT Process more than 1 Invitation at once !!!
    if ( _invitation != nil ) return;
    
    _invitation = [evt.params objectForKey:@"invitation"];
    _inviter = [_invitation inviter];
    
    // get Type of the Invitation
    SFSObject *sfsType = [_invitation params];
    NSString *invitationType = [sfsType getUtfString:INVITATION_TYPE];

    // Determine what Type is the Invitation
    if ( [invitationType isEqualToString:INVITATION_TYPE_BUDDY] ) {
        
        [self processBuddyInvitation:_invitation];
        
    } else if ( [invitationType isEqualToString:INVITATION_TYPE_GAME] ) {
        
        [self processGameInvitation:_invitation];
        
    } else {
        NSLog(@"###InvitationManager: onInvitation ERROR");
    }

}


// Called when you recieve reply for your Invitation
-(void)onInvitationReply:(SFSEvent *)evt
{
    
    // get Reply status
    NSInteger invitationReplyStatus = [[evt.params objectForKey:@"reply"] integerValue];
    SFSUser *invitee = [evt.params objectForKey:@"invitee"];
    
    // get Type of the Invitation
    SFSObject *sfsType = [evt.params objectForKey:@"data"];
    NSString *invitationType = [sfsType getUtfString:INVITATION_TYPE];
    
    // Determine what Type is the Invitation
    if ( [invitationType isEqualToString:INVITATION_TYPE_BUDDY] ) {
        
        [self processBuddyReplyInvitationWithStatus:invitationReplyStatus andInvetee:invitee];
        
    } else if ( [invitationType isEqualToString:INVITATION_TYPE_GAME] ) {
        
        [self processGameReplyInvitationWithStatus:invitationReplyStatus andInvetee:invitee];
        
    } else {
        NSLog(@"###InvitationManager: onInvitation ERROR");
    }
    
}


-(void)processBuddyInvitation:(SFSInvitation *)invitation
{
    
    NSString *message = [NSString stringWithFormat:@"%@ invites you to be your buddy.",_inviter.name];
    
    // Show Dialog to the user to make his decision
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Buddy Invitation" message:message delegate:self cancelButtonTitle:@"Refuse" otherButtonTitles:@"Accept", nil];
    
    // Set tag to 1 => BuddyInvitation AlertView is shown on screen (see "alertView: clickedButtonAtIndex:")
    alertView.tag = 1;
    [alertView show];
    
}


-(void)processGameInvitation:(SFSInvitation *)invitation
{
    
    NSString *message = [NSString stringWithFormat:@"%@ invites you to play together.",_inviter.name];
    
    // Show Dialog to the user to make his decision
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Game Invitation" message:message delegate:self cancelButtonTitle:@"Refuse" otherButtonTitles:@"Accept", nil];
    
    // Set tag to 2 => GameInvitation AlertView is shown on screen (see "alertView: clickedButtonAtIndex:")
    alertView.tag = 2;
    [alertView show];
    
}


-(void)processBuddyReplyInvitationWithStatus:(NSInteger)invitationReplyStatus andInvetee:(SFSUser *)invitee
{
    
    // Determine the status of Reply
    if ( invitationReplyStatus == InvitationReply_ACCEPT ) {
        
        // Invitation was ACCEPTED
        NSString *message = [NSString stringWithFormat:@"%@ accepted your invitation!",invitee.name];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invitation" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        
        
    } else if ( invitationReplyStatus == InvitationReply_REFUSE ) {
        
        // Invitation was REFUSED
        NSString *message = [NSString stringWithFormat:@"%@ refused your invitation!",invitee.name];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invitation" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        
    } else {
        
        // Invitation TimedOut
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invitation" message:@"Your invitation timed out." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    
}


-(void)processGameReplyInvitationWithStatus:(NSInteger)invitationReplyStatus andInvetee:(SFSUser *)invitee
{
    
    if ( _communicationManager.isInGame == YES ) {
        NSLog(@"Do Not show anything to the player when he is playng a Game !");
        return;
    }
    
    // Determine the status of Reply
    if ( invitationReplyStatus == InvitationReply_ACCEPT ) {
        
        // Present the Game to handle In game events.
// #warning Present the Game to handle In game events.
        
        // Invitation was ACCEPTED
        NSString *message = [NSString stringWithFormat:@"%@ accepted your invitation!",invitee.name];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Invitation" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        
    } else if ( invitationReplyStatus == InvitationReply_REFUSE ) {
        
        // Invitation was REFUSED
        NSString *message = [NSString stringWithFormat:@"%@ refused your invitation!",invitee.name];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Invitation" message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        
    } else {
        
        // Invitation TimedOut
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Game Invitation" message:@"Your invitation timed out." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        
    }
    
}


// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    // Determine which alertView is shown on screen
    if ( alertView.tag == 1 ) {
        // Buddy Invitation AlertView is shown
        
        // Refuse pressed
        if ( buttonIndex == 0 ) {
            
            // Replay to the Request so the sender will recive onInvitationReply:
            [self sendReply:InvitationReply_REFUSE forInvitation:_invitation withParams:nil];
            
        } else {
            // Accept pressed
            
            // Replay to the Request so the sender will recive onInvitationReply:
            [self sendReply:InvitationReply_ACCEPT forInvitation:_invitation withParams:nil];
            
        }
        
        // Invitation was processed so delete it. Now can be processsed next Invitation
        _invitation = nil;
        _inviter = nil;
        
    } else if ( alertView.tag == 2 ) {
        // Game Invitation AlertView is shown
        
        // Refuse pressed
        if ( buttonIndex == 0 ) {

            // Replay to the Request so the sender will recive onInvitationReply:
            [self sendReply:InvitationReply_REFUSE forInvitation:_invitation withParams:nil];
            
        } else {
            // Accept pressed
            
            // Present the Game to handle In game events.
// #warning Present the Game to handle In game events.
            
            // Replay to the Request so the sender will recive onInvitationReply:
            [self sendReply:InvitationReply_ACCEPT forInvitation:_invitation withParams:nil];
        }
        
        // Invitation was processed so delete it. Now can be processsed next Invitation
        _invitation = nil;
        _inviter = nil;
        
    }
    
}


// Send reply to the inviter
- (void)sendReply:(NSInteger)invitationReply forInvitation:(SFSInvitation *)invitation withParams:(SFSObject *)params
{
    [_smartFoxClient send:[InvitationReplyRequest requestWithInvitation:invitation invitationReply:invitationReply params:params]];
}


@end
